package com.linkage.bookshop.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.linkage.bookshop.model.Book;
import com.linkage.bookshop.model.Booktype;
import com.linkage.bookshop.model.Comment;
import com.linkage.bookshop.repository.UserRepository;
import com.linkage.bookshop.service.inter.BookService;
import com.linkage.bookshop.service.inter.CommentService;



@Controller
@RequestMapping("/book/*") 
public class BookController {
	@Resource
	BookService bookService;
	
	@Autowired
	private CommentService commentService;
	
	@Autowired
	private  UserRepository userRepository;
	
	@RequestMapping("/bookDetail/{bookId}")
	public String gotoBookDetail(HttpServletRequest request, HttpServletResponse response, Model model, @PathVariable("bookId") int bookId){
		Book book = this.bookService.loadBookDetail(bookId);
		Comment comment;
		List<String> userNames = new ArrayList<String>();
		List<Comment> comments = this.commentService.listBookComments(bookId);
		Iterator<Comment> iter = comments.iterator();
		int id;
		//FIXME
		while (iter.hasNext()){
			comment = (Comment)iter.next();
			id = comment.getUserId();
			userNames.add(this.userRepository.selectUsernameById(id));
		}
		model.addAttribute("book", book);
		model.addAttribute("imgPath", book.getImagePath());
		model.addAttribute("comments", comments);
		model.addAttribute("userNames", userNames);
		return "book_detail";
	}
	
	@RequestMapping("/bookDetailAdmin/{bookId}")
	public String gotoBookDetailAdmin(HttpServletRequest request, HttpServletResponse response, Model model, @PathVariable("bookId") int bookId){
		Book book = this.bookService.loadBookDetail(bookId);
		model.addAttribute("book", book);
		
		return "book_detailAdmin";
	}
	
	@RequestMapping(value = "/bookListByType/{typeId}")
	public String listBooksByType(Model model, @PathVariable("typeId") int typeId){
		
		List<Book> bookList = this.bookService.listAllBooksOnsale(typeId);
		model.addAttribute("books", bookList);
		return "list";
	}
	
	@RequestMapping(value = "/booksList")
	public String bookList (Model model){	
		List<Book> bookList = this.bookService.listAllBooks();
		model.addAttribute("books", bookList);
		return "listBooksAdmin";
	}
	
	@RequestMapping(value = "/bookListByTypeAdmin/{typeId}")
	public String listBooksByTypeAdmin(Model model, @PathVariable("typeId") int typeId){
		List<Book> bookList = this.bookService.listAllBooks(typeId);
		model.addAttribute("books", bookList);
		return "listBooksAdmin";
	}
	
	@RequestMapping(value = "/bookListByKeyWord", method = RequestMethod.POST)
	public String listBooksByKeyWord(Model model, @RequestParam("keyword") String keyWord){
		List<Book> bookList = this.bookService.listAllBooksOnsale(keyWord);
		model.addAttribute("books", bookList);
		return "list";
	}
	
	@RequestMapping(value = "/bookListByKeyWordAdmin", method = RequestMethod.POST)
	public String listBooksByKeyWordAdmin(Model model, @RequestParam("keyword") String keyWord){
		List<Book> bookList = this.bookService.listAllBooks(keyWord);
		model.addAttribute("books", bookList);
		return "listBooksAdmin";
	}
	
	@RequestMapping(value = "/findBooks" )
	public ModelAndView findBooks(HttpServletRequest request, Model model){
		ModelAndView mav = new ModelAndView("admin_search");
		List<Booktype> types = this.bookService.listAllTypes();
		model.addAttribute("types", types);
		return mav;
	}
	
	@RequestMapping(value = "/modifyOnSale" )
	public String  modifyOnsale(@RequestParam("onSale") boolean onSale, @RequestParam("id") int id){
		if(onSale){
			bookService.pullBook(id);
		}else{
			bookService.pushBook(id);
		}
		
		return "redirect:booksList";
		
	}
	
	@RequestMapping(value = "/modifyBook" )
	public String  modifyBook(@RequestParam("id") int id,Model model){
		Book book = bookService.loadBookDetail(id);
		List<Booktype> booktypes = bookService.listAllTypes();
		model.addAttribute("booktypes", booktypes);
		model.addAttribute("book",book);
		return "edit_book";
		
	}
	
	@RequestMapping(value = "/modifyBookDo" )
	public String  modifyBookDo(HttpServletRequest httpServletRequest){
		Book book = new Book();
		book.setOutPrice(Double.valueOf(httpServletRequest.getParameter("outPrice")));
		book.setStorageVolume(Integer.valueOf(httpServletRequest.getParameter("storageVolume")));
		book.setId(Integer.valueOf(httpServletRequest.getParameter("id")));
		bookService.modifyBook(book);
		return "redirect:booksList";
		
	}
	
	@RequestMapping(value = "/manageGoods", produces = "application/json", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> manageGoods (){
		Map<String, Object> params = new HashMap<>();
		params.put("result", true);
		return params;
	}
	
	@RequestMapping(value = "/checkBooktype/{name}", produces = "application/json", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> checkBooktype (@PathVariable("name") String name){
		Map<String, Object> params = new HashMap<>();
		boolean result = bookService.checkTypeName(name);
		params.put("result", result);
		return params;
	}
	
	@RequestMapping(value = "/addBooktype/{name}", produces = "application/json", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> addBooktype (@PathVariable("name") String name){
		Map<String, Object> params = new HashMap<>();
		boolean result = bookService.addType(name);
		params.put("result", result);
		return params;
	}		
	
	@RequestMapping(value = "/listBooktypes", produces = "application/json", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> listBooktypes (){
		Map<String, Object> params = new HashMap<>();
		List<Booktype> booktypes = bookService.listAllTypes();
		params.put("booktypes", booktypes);
		return params;
	}		
	
	@RequestMapping(value = "/addBook", produces = "application/json", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> addBook (@RequestParam("book") String book){
		Map<String, Object> params = new HashMap<>();
		JSONObject json = JSONObject.fromObject(book);
		Book b = new Book();
		Booktype booktype= new Booktype();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		b.setAuthor(json.getString("author"));
		b.setDescription(json.getString("description"));
		b.setInPrice(json.getDouble("inPrice"));
		b.setName(json.getString("name"));
		b.setOutPrice(json.getDouble("outPrice"));
		booktype.setId(json.getInt("typeId"));
		b.setBooktype(booktype);
		b.setPress(json.getString("press"));
		try {
			b.setPublishTime(sdf.parse(json.getString("publishTime")));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		b.setStorageVolume(json.getInt("storageVolume"));
		b.setSaleVolume(0);
		b.setOnsaleFlag(Boolean.valueOf(json.getString("onsaleFlag")));
		boolean result = bookService.addBook(b);
		return params;
	}		
	
}